<?php

namespace Usap\Service\Common;

use Usap\Service\Service;

class crontal
{
    /**
     * @param
     * 获取巡检任务列表
     */
    public function getCheckTaskList($where, $page, $rows, $order, $sort, $files = '*')
    {
        $this->checkTaskIsExpire();//TODO 服务器启用定时任务 每日凌晨调用
        $model = D("Usap/Common/CheckTask");
        $orders = $order . ' ' . $sort;
        $count = $model->alias('a')->join('left join devices as b on a.device_id = b.device_id left join `user` as c on a.user_id = c.user_id')->where($where)->count();
        if ($count > 0) {
            $list = $model->field($files)->alias('a')->join('left join devices as b on a.device_id = b.device_id left join `user` as c on a.user_id = c.user_id')
                ->where($where)->page($page, $rows)->order($orders)->select();
        } else {
            $count = 0;
            $list = [];
        }
        return array('count' => $count, 'list' => $list);
    }

    /**
     * 通过ID获取指定巡检任务
     * @param int $id
     */
    public function getCheckTaskInfoById($id)
    {
        $model = D("Usap/Common/CheckTask");
        return $model->where(['id' => $id])->find();
    }

    /**
     * 更新巡检任务
     */
    public function updateCheckTaskInfo($id, $data, $device_id = '')
    {
        $device_service = Service::instance()->find('devices', 'devices');
        $model = D("Usap/Common/CheckTask");
        if ($device_id) {
            $info = ['last_check_time' => date('Y-m-d H:i:s')];
            $device_service->updateDevice($device_id, $info);
            $device_service->buildCheckTask($device_id);
        }
        $res = $model->where(['id' => $id])->save($data);
        return $res;
    }

    /**
     * 定时更新过期任务
     */
    public function checkTaskIsExpire()
    {
        $device_sevice = Service::instance()->find('devices', 'devices');
        $model = D("Usap/Common/CheckTask");
        $date = date('Y-m-d H:i:s');
        $where = " end_time < '$date' and status not in (2,3,4)";
        $list = $model->where($where)->select();
        $ids = [];
        if ($list) {
            foreach ($list as $value) {
                $ids[] = $value['device_id'];
                $id = $value['id'];
                //对过期的任务进行更新状态
                $update = [
                    'status' => 4
                ];
                $this->updateCheckTaskInfo($id, $update);
                //生成新的巡检任务
                $device_sevice->buildCheckTask($value['device_id']);
            }
        }
    }
}